package com.clothes.act;

import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.clothes.R;
import com.clothes.adp.Cadapter;
import com.clothes.app.BaseUrl;
import com.clothes.http.JsonCallBack;
import com.clothes.mdoel.ColorInfo;
import com.clothes.mdoel.ServerInfo;
import com.clothes.utils.DateTool;
import com.clothes.views.CustomListView;
import com.clothes.views.pull.PullToRefreshLayout;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;

public class CSearch extends BaseActivity {

    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_begin_time)
    TextView tvBeginTime;
    @Bind(R.id.tv_end_time)
    TextView tvEndTime;
    @Bind(R.id.et_num)
    EditText etNum;
    @Bind(R.id.lv_c)
    CustomListView lvC;
    @Bind(R.id.refresh_view)
    PullToRefreshLayout refreshView;
    @Bind(R.id.tv_all_one)
    TextView tvAllOne;
    @Bind(R.id.tv_all_two)
    TextView tvAllTwo;
    @Bind(R.id.tv_all_three)
    TextView tvAllThree;
    @Bind(R.id.tv_all_four)
    TextView tvAllFour;
    @Bind(R.id.ll_add_size)
    LinearLayout llAddSize; //尺码明细
    @Bind(R.id.ll_size)
    LinearLayout llSize;

    private List<ColorInfo> list = new ArrayList<>();
    private List<ColorInfo> listAll = new ArrayList<>();
    private List<ColorInfo> listResult = new ArrayList<>(); //转换后的list
    private Cadapter adapter;

    @Override
    public void initView() {
        setContentView(R.layout.activity_csearch);
        tvTitle.setText("交货统计表");
    }

    @Override
    public void initData() {
        setTime(3);
        tvBeginTime.setText(DateTool.getStringDate(System.currentTimeMillis(),"yyyy-MM-dd"));
        tvEndTime.setText(DateTool.getStringDate(System.currentTimeMillis(),"yyyy-MM-dd"));
        mImmersionBar.statusBarColor(R.color.colorPrimaryDark).init();
        adapter = new Cadapter(this,list);
        lvC.setAdapter(adapter);
        getAllSize();

        //禁止上啦 下拉
        refreshView.setPullUpEnable(false);
        refreshView.setPullDownEnable(false);

        refreshView.setOnPullListener(new PullToRefreshLayout.OnPullListener() {
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                // 下拉刷新操作
                refresh();
            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                // 下拉刷新操作
                loadMore();
            }
        });

        etNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if(charSequence.toString().equals("")){
                    refreshView.setPullDownEnable(false);
                }else {
                    refreshView.setPullDownEnable(true);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    //刷新
    private void refresh(){
        pageNum = 0;
        refreshView.setPullUpEnable(true);
        getHttp();
    }
    //加载
    private void loadMore(){
        pageNum++;
        getHttp();
    }

    @OnClick({R.id.iv_back, R.id.tv_begin_time, R.id.tv_end_time, R.id.iv_search,
            R.id.tv_all_one, R.id.tv_all_two, R.id.tv_all_three, R.id.tv_all_four,R.id.ll_size})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                onBackPressed();
                break;
            case R.id.tv_begin_time:
                t = 1;
                timePickerView.show();
                break;
            case R.id.tv_end_time:
                t= 2;
                timePickerView.show();
                break;
            case R.id.iv_search:
                getHttp();
                break;
            case R.id.tv_all_one:
                break;
            case R.id.tv_all_two:
                break;
            case R.id.tv_all_three:
                break;
            case R.id.tv_all_four:
                break;
            case R.id.ll_size:
                hideSize();
                break;
        }
    }

    private int t;
    @Override
    protected void setTimeText(String time) {
        if(t == 1)
            tvBeginTime.setText(time);
        else
            tvEndTime.setText(time);
    }

    //请求网络
    private void getHttp(){
        String num = etNum.getText().toString();
        if(num.equals("")){
            showToast("请输入款号");
            return;
        }
        OkGo.<ServerInfo<List<ColorInfo>>>get(BaseUrl.CSerch)
                .params("modelNumber",num)
                .params("pageIndex",pageNum)
                .params("pageSize",pageSize)
                .params("beginDate",tvBeginTime.getText().toString())
                .params("endDate",tvEndTime.getText().toString()+" 23:59")
                .execute(new JsonCallBack<ServerInfo<List<ColorInfo>>>() {
                    @RequiresApi(api = Build.VERSION_CODES.N)
                    @Override
                    public void onSuccess(Response<ServerInfo<List<ColorInfo>>> response) {
                        if(pageNum == 0) {
                            refreshView.refreshFinish(PullToRefreshLayout.SUCCEED);
                            listAll.clear();
                        }else {
                            refreshView.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                        }
                        ServerInfo serverInfo = response.body();
                        list = (List<ColorInfo>) serverInfo.getData();
                        if(list.size() < 20){
                            if(pageNum > 0){
                                showToast("数据已经全部加载");
                            }
                            refreshView.setPullUpEnable(false);
                        }else {
                            refreshView.setPullUpEnable(true);
                        }

                        listAll.addAll(list);
                        listResult = setList(listAll);
                        adapter.setList(listResult);
                        getAllSize();
                    }

                    @Override
                    public void onError(Response<ServerInfo<List<ColorInfo>>> response) {
                        if(pageNum == 0)
                            refreshView.refreshFinish(PullToRefreshLayout.SUCCEED);
                        else
                            refreshView.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                        showToast("服务器请求失败");
                    }
                });
    }

    // 显示尺码
    public void showSize(Map<String,Integer> map){
        llSize.setVisibility(View.VISIBLE);
        showList(map);
    }

    //隐藏尺码
    private void hideSize(){
        llSize.setVisibility(View.GONE);
    }

    //获取列表所有合计
    private void getAllSize(){
        int one = 0,two = 0,three = 0,four = 0;
        for (ColorInfo table : listResult){
            one += table.getColorUnClaimed();
            two += table.getColorClaimed();
            three += table.getColorSubmit();
            four += (table.getColorUnClaimed()+table.getColorClaimed());
        }
        tvAllOne.setText(one+"件");
        tvAllTwo.setText(two+"件");
        tvAllThree.setText(three+"件");
        tvAllFour.setText(four+"件");
    }

    private List<ColorInfo> setList(List<ColorInfo> colorInfoList) {
        List<ColorInfo> resultList = new ArrayList<>();
        if(colorInfoList!=null&&!colorInfoList.isEmpty()) {
            Map<String, List<ColorInfo>> listMap = new HashMap<>();// colorInfoList.stream().collect(Collectors.groupingBy(item -> item.getColorName()));

            for(ColorInfo color:colorInfoList){
                if(listMap.get(color.getColorName())!=null){
                    List<ColorInfo> list = listMap.get(color.getColorName());
                    list.add(color);
                }else{
                    List<ColorInfo> list = new ArrayList<>();
                    list.add(color);
                    listMap.put(color.getColorName(),list);
                }
            }


            //颜色分组
            for (Map.Entry<String, List<ColorInfo>> entry : listMap.entrySet()) {
                String key = entry.getKey().toString();
                ColorInfo colorInfo = new ColorInfo();
                List<ColorInfo> valueList = entry.getValue();
                colorInfo.setColorName(key);

                Integer  colorClaimed= 0;
                Integer  colorSubmit= 0;
                Map<String,Integer> sizeClaimedMap = new HashMap(); // 尺码已领List
                Map<String,Integer> sizeSubmitMap = new HashMap(); // 尺码已交List
                Map<String,Integer> sizeUnClaimedMap = new HashMap();// 尺码未领List
                Map<String,Integer> sizeCountMap = new HashMap();// 尺码合计z


                for(ColorInfo color:valueList){
                    colorClaimed=colorClaimed.intValue()+color.getColorClaimed();
                    colorSubmit=colorSubmit.intValue()+color.getColorSubmit();
                    if(sizeClaimedMap.get(color.getSizeName())!=null){
                        sizeClaimedMap.put(color.getSizeName(),color.getSizeClaimed()+sizeClaimedMap.get(color.getSizeName()));
                    }else{
                        sizeClaimedMap.put(color.getSizeName(),color.getSizeClaimed());
                    }
                    if(sizeSubmitMap.get(color.getSizeName())!=null){
                        sizeSubmitMap.put(color.getSizeName(),color.getSizeSubmit()+sizeSubmitMap.get(color.getSizeName()));
                    }else{
                        sizeSubmitMap.put(color.getSizeName(),color.getSizeSubmit());
                    }
                    if(sizeUnClaimedMap.get(color.getSizeName())!=null){
                        sizeUnClaimedMap.put(color.getSizeName(),color.getSizeNum()-sizeClaimedMap.get(color.getSizeName()));
                    }else{
                        sizeUnClaimedMap.put(color.getSizeName(),color.getSizeNum()-color.getSizeClaimed());
                    }
                    sizeCountMap.put(color.getSizeName(),color.getSizeNum());
                }

                colorInfo.setSizeClaimedMap(sizeClaimedMap);
                colorInfo.setSizeUnClaimedMap(sizeUnClaimedMap);
                colorInfo.setSizeSubmitMap(sizeSubmitMap);
                colorInfo.setSizeCountMap(sizeCountMap);
                colorInfo.setColorClaimed(colorClaimed);
                colorInfo.setColorSubmit(colorSubmit);

                if(valueList.size() > 0) {
                    colorInfo.setModelNumber(valueList.get(0).getModelNumber());
                    colorInfo.setColorUnClaimed(valueList.get(0).getColorNum() - colorClaimed);
                    colorInfo.setColorNum(valueList.get(0).getColorNum());
                }

                resultList.add(colorInfo);
            }
        }
        return resultList;
    }

    private void showList(Map<String,Integer> map){
        llAddSize.removeAllViews();
        Iterator it = map.entrySet().iterator();
        while (it.hasNext()){
            Map.Entry entry = (Map.Entry) it.next();
            String name = (String) entry.getKey();
            int value = (int) entry.getValue();
            TextView textView = new TextView(this);
            textView.setText(name+": "+value+"件");
            textView.setPadding(0,3,0,3);
            llAddSize.addView(textView);
        }
    }
}
